package thread;

import javafx.scene.layout.Priority;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class ProducerAndConsumer {
    static List<String> list = new ArrayList<String>();

    public static void main(String[] args) {
        new Thread(new Producer(),"生产者").start();
        new Thread(new Consumer(),"消费者").start();
    }
}

class Producer implements Runnable{

    @Override
    public void run() {

        synchronized (ProducerAndConsumer.list) {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ProducerAndConsumer.list.size() >= 10) {
                    System.out.println("仓库已经满了.....");
                    ProducerAndConsumer.list.notify();
                    try {
                        ProducerAndConsumer.list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName()+":生产物资");
                    ProducerAndConsumer.list.add(Thread.currentThread().getName() + ":生产物资");
                }
            }
        }

    }
}

class Consumer implements Runnable{

    @Override
    public void run() {
        synchronized (ProducerAndConsumer.list) {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ProducerAndConsumer.list.size() <= 0) {
                    System.out.println(Thread.currentThread().getName() + ":物资紧缺");
                    ProducerAndConsumer.list.notify();
                    try {
                        ProducerAndConsumer.list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println(Thread.currentThread().getName()+":消费物资");
                    ProducerAndConsumer.list.remove(0);
                }
            }
        }
    }
}
